package main

import (
	"log/slog"
	"os"

	"github.com/BurntSushi/toml"
	"github.com/prometheus/client_golang/prometheus"
)

var (
	// Config
	Config = &_config{
		ListeningAddr:    ":9527",
		MetricsURLPath:   "/metrics",
		ScrapeTimeoutSec: 10.0,
		DeviceDefaultParameters: RDLDevice{
			Port:       80,
			Username:   "superuser",
			Password:   "123",
			HTTPScheme: "http",
		},
		Devices: []*RDLDevice{
			{
				Host:       "192.168.10.251",
				Port:       443,
				Username:   "superuser",
				Password:   "123",
				HTTPScheme: "https",
			},
			{Host: "192.168.10.252"},
		},
	}

	// ConfigFile
	ConfigFile = "config.toml"

	// allRegisteredGaugeCollectors 所有注册的GaugeVec, 每次请求前需要重置
	allRegisteredGaugeCollectors = make([]*prometheus.GaugeVec, 0, 64)
)

// _config 配置文件结构体
type _config struct {
	ListeningAddr           string       `toml:"listening_addr"`
	MetricsURLPath          string       `toml:"metrics_url_path"`
	ScrapeTimeoutSec        float64      `toml:"scrape_timeout_sec"`
	DeviceDefaultParameters RDLDevice    `toml:"device_default_parameters"`
	Devices                 []*RDLDevice `toml:"devices"`
}

func init() {
	// 加载配置文件
	if _, err := toml.DecodeFile(ConfigFile, &Config); err != nil {
		if os.IsNotExist(err) {
			slog.Error("Config file does not exist.", "file", ConfigFile)

			file, err := os.Create(ConfigFile + ".example")
			if err != nil {
				panic(err)
			}
			enc := toml.NewEncoder(file)
			enc.Indent = "    "
			if err := enc.Encode(Config); err != nil {
				panic(err)
			}

			slog.Warn("Please create the config file and fill it in, the example file is for your reference.")
			os.Exit(1)
		}

		slog.Error("Failed to load config file, please refer to the example file to fix it.", "file", ConfigFile)
		os.Exit(1)
	}
	slog.Info("Successfully loaded config file.", "file", ConfigFile)

	// 检查配置文件
	for _, device := range Config.Devices {
		if device.Host == "" {
			slog.Error("Configuration error, Host must not be empty")
			os.Exit(1)
		}

		if device.Username == "" {
			device.Username = Config.DeviceDefaultParameters.Host
		}
		if device.Password == "" {
			device.Password = Config.DeviceDefaultParameters.Password
		}
		if device.HTTPScheme == "" {
			device.HTTPScheme = Config.DeviceDefaultParameters.HTTPScheme
		}
		if device.Port == 0 {
			device.Port = Config.DeviceDefaultParameters.Port
		}
	}

	// 注册指标
	for _, metric := range []prometheus.Collector{
		// 抓取相关指标
		MetricOnlineStatus, MetricScrapeFailuresTotal, MetricPingResponseTime, MetricAPIResponseTime,

		// 设备相关指标
		MetricCPUUsage, MetricMemoryUsage, MetricTemperature, MetricUptime, MetricBaseInfo, MetricVPNConnectionStatus,
	} {
		prometheus.MustRegister(metric)

		if gaugeVec, ok := metric.(*prometheus.GaugeVec); ok {
			allRegisteredGaugeCollectors = append(allRegisteredGaugeCollectors, gaugeVec)
		}
	}
}
